﻿using System.Security.Cryptography;
using System.Text;
using PhiStore.Util;

namespace PhiStore.Security
{
    /// <summary>
    /// Static class containing various helper functions for cryptography / oneway hashes
    /// </summary>
    public static class Helper
    {
        /// <summary>
        /// Generates a key from a text
        /// </summary>
        /// <param name="text">The text used</param>
        /// <param name="bits">key length in bits</param>
        /// <returns>The generated key</returns>
        public static byte[] GenerateKey(string text, int bits)
        {
            byte[] salt = Encoding.ASCII.GetBytes("_#Phi!Store^Rulez*¤1337");
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(text, salt);
            return DerivedPassword.GetBytes(bits / 8);
        }

        /// <summary>
        /// Generates an initialization vector from a text
        /// </summary>
        /// <param name="text">The text used</param>
        /// <param name="bits">IV length in bits</param>
        /// <returns>The generated initialization vector</returns>
        public static byte[] GenerateIV(string text, int bits)
        {
            byte[] salt = Encoding.ASCII.GetBytes("Rulez_Does!Phi#Store?");
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(text, salt);
            return DerivedPassword.GetBytes(bits / 8);
        }

        /// <summary>
        /// Generates a key
        /// </summary>
        /// <param name="bits">key length in bits</param>
        /// <returns></returns>
        public static byte[] GenerateKey(int bits)
        {
            byte[] result = RandomGenerator.Bytes(bits / 8);
            return result;
        }


        /// <summary>
        /// Calculates and returns the MD5 Hash
        /// </summary>
        /// <param name="input">An ASCII interpreted string</param>
        /// <returns>The MD5 hash</returns>
        public static byte[] MD5(string input)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            return md5.ComputeHash(Encoding.ASCII.GetBytes(input));
        }

        /// <summary>
        /// Calculates and returns the SHA256 Hash
        /// </summary>
        /// <param name="input">An ASCII interpreted string</param>
        /// <returns>The SHA256 hash</returns>
        public static byte[] SHA256(string input)
        {
            SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider();
            return sha.ComputeHash(Encoding.ASCII.GetBytes(input));
        }

    }
}
